import axios, { AxiosRequestConfig } from 'axios'
import { message } from 'ant-design-vue'
import { getToken } from './helper/cookieHelper'
import { ResponseDataType } from '@/types/response'

const instance = axios.create({
  baseURL: '/api'
})

instance.interceptors.request.use(config => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

const request = async <T = any>(config: AxiosRequestConfig): Promise<ResponseDataType<T>> => {
  try {
    const { data } = await instance.request<ResponseDataType>(config)
    // 消息提示
    data.code === 0
      ? data.message && message.success(data.message)
      : message.error(data.message) // 请求失败应当有消息提示
    return data
  } catch (err: any) {
    const msg = err.message || '请求失败'
    console.error(msg)
    return {
      code: -1,
      message: msg,
      data: null as any // 仅用于通过类型校验，请求失败的情况下不应使用对象中的data属性
    }
  }
}

export default request
